package com.zcxy360.sandtable.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcxy360.sandtable.domain.Org;
import com.zcxy360.sandtable.domain.OrgExample;
import com.zcxy360.sandtable.domain.OrgMapper;
import com.zcxy360.sandtable.domain.User;
import com.zcxy360.sandtable.domain.UserMapper;
import com.zcxy360.sandtable.util.PasswordUtil;
import com.zcxy360.sandtable.util.ShiroUtil;
import com.zcxy360.sandtable.util.StringUtil;

@Transactional
@Service
public class OrgService {

	@Autowired
	private OrgMapper orgMapper;
	@Autowired
	private UserMapper userMapper;

	public Org getByOrgId(Integer orgId) {
		return orgMapper.selectByPrimaryKey(orgId);
	}

	public Object list(Org org, String key, String orderByClause, Integer pageNum, Integer pageSize, Integer navigatePages) {
		PageHelper.startPage(pageNum,pageSize);
		List<Org> orgs = orgMapper.listWithExtra(org,StringUtil.wrapper(key),orderByClause);
		return new PageInfo<>(orgs, navigatePages);
	}

	public Org post(Org org) {
		orgMapper.insertSelective(org);
		
		User loginUser = ShiroUtil.getUser();
		User manager = new User();
		manager.setCreatorId(loginUser.getUserId());
		manager.setRole("manager");  
		manager.setRealName(org.getLegalPerson());
		manager.setOrgId(org.getOrgId());
		manager.setPhone(org.getCellphone());
		manager.setMail(org.getMail());
		manager.setPassword(StringUtil.generateDefaultPassword(org.getCellphone()));
		PasswordUtil.encryptPassword(manager);
		userMapper.insertSelective(manager);
		
		return org;
	}

	public boolean update(Org org) {
		User user = userMapper.selectLegalPerson(org.getOrgId());
		String realName = org.getLegalPerson();
		String cellphone = org.getCellphone();
		boolean flag = false;
		if(StringUtil.isNotEmpty(realName) && !user.getRealName().equals(realName)) {
			user.setRealName(realName);
			flag = true;
		}
		if(StringUtil.isNotEmpty(cellphone) && !user.getPhone().equals(cellphone)) {
			user.setPhone(cellphone);
			flag = true;
		}
		if(flag) {
			userMapper.updateByPrimaryKeySelective(user);
		}
		orgMapper.updateByPrimaryKeySelective(org);
		//如果修改有效期,则调用resetTerm函数更新该机构可用状态及对用用户锁定状态
		if(org.getTerm() != null) {
			orgMapper.resetTerm(org.getOrgId());
		}
		return true;
	}

	public boolean delete(int[] orgIds) {
		orgMapper.deleteBatch(orgIds);
		return true;
	}

	public boolean checkName(String name) {
		OrgExample ex = new OrgExample();
		ex.or().andNameEqualTo(name);
		return orgMapper.countByExample(ex) == 0;
	}
	
}
